package org.demo.szml.userservice.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.demo.szml.api.exception.ApiInvokePersistentException;
import org.demo.szml.userservice.repository.IUserRepository;
import org.demo.szml.userservice.repository.mapper.UsersMapper;
import org.demo.szml.userservice.repository.po.UsersPO;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;

/**
 * @description: 用户仓储实现类
 * @date: 2025/6/15 22:54
 * @version: 1.0
 */
@Slf4j
@Component
public class UserRepositoryImpl implements IUserRepository {

    private final UsersMapper usersMapper;

    public UserRepositoryImpl(UsersMapper usersMapper){
        this.usersMapper = usersMapper;
    }

    @Override
    public Long saveNewUser(UsersPO user) {
        int insert = 0;
        try {
            insert = usersMapper.insert(user);
        } catch (DuplicateKeyException e) {
            log.error("触发唯一键约束-用户名已存在:{}",user.getUsername());
            throw new ApiInvokePersistentException("此用户名已存在");
        }
        if(insert == 1){
            return user.getUserId();
        }
        return null;
    }

    @Override
    public UsersPO selectUserPassword(String username) {
        return usersMapper.selectOne(new LambdaQueryWrapper<UsersPO>()
                .select(UsersPO::getPassword, UsersPO::getUserId)
                .eq(UsersPO::getUsername, username));
    }

    @Override
    public List<UsersPO> getUserInfoById(List<Long> userIds) {
        List<UsersPO> usersPOS = usersMapper.selectList(new LambdaQueryWrapper<UsersPO>()
                .select(UsersPO::getUsername, UsersPO::getUserId, UsersPO::getPhone, UsersPO::getEmail)
                .in(UsersPO::getUserId, userIds));
        if(ObjectUtils.isEmpty(usersPOS)){
            return Collections.emptyList();
        }
        return usersPOS;
    }

    @Override
    public int modifyUserInfo(UsersPO user) {
        return usersMapper.update(user,new LambdaUpdateWrapper<>());
    }
}
